/*--------------------------------------------------------------
 * File: sntp_task.c 编码类型：C语言  UTF-8
 * Author WRS (1352509846@qq.com)
 * 功能: NTP网络校时功能
 * Version 0.1
 * Date 2024-05-07
 *
 * @copyright Copyright (c) 2024
 *
----------------------------------------------------------------*/
#include "sntp_task.h"
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "nvs_flash.h"
#include "esp_sntp.h"
#include "esp_netif_sntp.h"

static const char *TAG = "example";

void time_sync_notification_cb(struct timeval *tv)
{
    time_t now;
    struct tm timeinfo;
    char strftime_buf[64];

    ESP_LOGI(TAG, "Notification of a time synchronization event");
    time(&now);
    localtime_r(&now, &timeinfo);
    // Set timezone to China Standard Time
    setenv("TZ", "CST-8", 1);
    tzset();
    localtime_r(&now, &timeinfo);
    strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
}

static void initialize_sntp(void)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("ntp.aliyun.com");
    config.sync_cb = time_sync_notification_cb;     // Note: This is only needed if we want
    // sntp_setservername(0, "ntp.aliyun.com");
    // sntp_set_time_sync_notification_cb(time_sync_notification_cb);
    // sntp_init();
    esp_netif_sntp_init(&config);
}

static void obtain_time(void)
{
    initialize_sntp();  
}

void update_time_task(void *pvParameter)
{  
    time_t now;
    struct tm timeinfo;

    // Update time every day at 00:00
    while (1)
    {    
        time(&now);
        localtime_r(&now, &timeinfo);
        if (timeinfo.tm_hour == 0 && timeinfo.tm_min == 0)
        {
            initialize_sntp();
        }
        vTaskDelay(pdMS_TO_TICKS(30000)); // Check every 30s
    }
}

void sntp_task_init(void)
{
    time_t now;
    struct tm timeinfo;
    time(&now);
    localtime_r(&now, &timeinfo);
    // Is time set? If not, tm_year will be (1970 - 1900).
    if (timeinfo.tm_year < (2024 - 1900))
    {
        ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
        obtain_time();
        // update 'now' variable with current time
        time(&now);
        // xTaskCreate(&update_time_task, "update_time_task", 4096, NULL, 5, NULL);
    }
}

